package com.xd.core.system.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.SecurityUtil;
import com.xd.core.system.dto.*;
import com.xd.core.system.entity.SysRole;
import com.xd.core.system.entity.SysUserRole;
import com.xd.core.system.service.ISysRoleService;
import com.xd.core.system.service.ISysUserRoleService;
import com.xd.core.system.vo.SysRoleVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author SJ
 * @since 2023-03-17
 */
@Slf4j
@Api(tags = "角色信息")
@RestController
@RequestMapping("/sys-role")
public class SysRoleController {

    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${sysRoleIds}")
    private List<Integer> sysRoleIds;
    private static final String redisLogin = "login:";
    private static final String redisToken = "token:";

    @PreAuthorize("hasAuthority('sys:AddRole')")
    @ApiOperation("新增角色")
    @PostMapping("/addRole")
    public void addRole(@RequestBody InsertRoleDto insertRoleDto) {
        iSysRoleService.addRole(insertRoleDto);
        log.info("新增角色成功");
    }

    /*
    * 添加权限需要重新登陆
    * 减少权限不需要重新登陆
    * */

    @PreAuthorize("hasAuthority('sys:UpdataRole')")
    @ApiOperation("修改角色")
    @PostMapping("/updateRole")
    public void updateRole(@RequestBody UpdateRoleDto updateRoleDto) {
        iSysRoleService.updateRole(updateRoleDto);
        log.info("修改角色成功");
    }
    @PreAuthorize("hasAnyAuthority('sys:RoleManagement-Delete')")
    @ApiOperation("删除角色")
    @DeleteMapping("/deleteRole")
    public void deleteRole(Integer id) {
        if (sysRoleIds.contains(id))
            throw new XkdException("无法删除系统角色");
        iSysRoleService.deleteRole(id);
    }

    @PreAuthorize("hasAnyAuthority('sys:RoleManagement','sys:SystemAdministration')")
    @ApiOperation("角色列表")
    @PostMapping("/roleList")
    public Page<SysRole> roleList(@RequestBody RoleListDto roleListDto) {
        return iSysRoleService.roleList(roleListDto);
    }

//    @ApiOperation("员工管理--角色下拉框")
//    @GetMapping("/roleDownList")
//    public List<SysRoleVo> roleList() {
//        Integer companyId = SecurityUtil.getLoginCompanyId();
//        return BeanUtil.copyToList( iSysRoleService.list(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCompanyId,companyId)),SysRoleVo.class);
//    }

    @ApiOperation("角色修改状态")
    @PostMapping("/updateStatus")
    public void updateStatus(@RequestBody UpdateStatusDto updateStatusDto) {
        if (sysRoleIds.contains(updateStatusDto.getId()))
            throw new XkdException("无法修改系统角色");
        SysRole sysRole = new SysRole();
        sysRole.setId(updateStatusDto.getId());
        sysRole.setStatus(updateStatusDto.getStatus());
        iSysRoleService.updateById(sysRole);
        //强制下线
        if (updateStatusDto.getStatus().equals(SysConstant.XKD_STATUS_DEACTIVATE)) {
            List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getRoleId, updateStatusDto.getId())
                    .eq(SysUserRole::getCompanyId, SecurityUtil.getLoginCompanyId()));
            List<Integer> collect = list.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
            collect.forEach(userId -> {
                redisTemplate.delete(redisLogin + userId);
                redisTemplate.delete(redisToken + userId);
            });
        }

    }


}
